package com.lxy.demo;

import redis.clients.jedis.Jedis;

import java.util.Random;

public class redisCode {

    //获取六位验证码
    public static String getCode(){
        String code  = "";
        Random random = new Random();
        for (int i = 0; i < 6 ; i++) {
            int num = random.nextInt(10);
            code += num;
        }
        return code;
    }

    //保存验证码，时效两分钟，一天的保存时间
    public static void saveRedis(String num){
        Jedis jedis = new Jedis("192.168.40.133",6379);
        jedis.auth("0000");
        String numCount = num + ":count";
        String numCode = num + ":Code";
        //先获取次数的值
        String s = jedis.get(numCount);
        if (s == null){
            //第一次设置值setex(键,时间,值);
            jedis.setex(numCount,60*60*24,"1");
        }else if(Integer.parseInt(s) < 3){
            //incr使值加一
            jedis.incr(numCount);
        }else if (Integer.parseInt(s) >= 3){
            System.out.println("今日的次数已经用完");
            jedis.close();
            return;
        }
        jedis.setex(numCode,120,getCode());
    }

    //判断验证吗正确以及失效
    public static void checkCode(String num,String code){
        Jedis jedis = new Jedis("192.168.40.133",6379);
        jedis.auth("0000");
        String numCode = num + ":Code";
        String s = jedis.get(numCode);
        if (s.equals(code)){
            System.out.println("验证成功");
        }else {
            System.out.println("验证失败");
        }

    }

    public static void main(String[] args) {
        String num = "15572241551";
        //saveRedis(num);
        checkCode(num,"802759");
    }
}
